package utils

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

// Config 应用配置结构
type Config struct {
	Server struct {
		Port int    `yaml:"port"`
		Mode string `yaml:"mode"`
	} `yaml:"server"`

	Database struct {
		Type  string `yaml:"type"`
		MySQL struct {
			Host        string `yaml:"host"`
			Port        int    `yaml:"port"`
			Username    string `yaml:"username"`
			Password    string `yaml:"password"`
			DBName      string `yaml:"dbname"`
			Charset     string `yaml:"charset"`
			MaxIdleConn int    `yaml:"max_idle_conns"`
			MaxOpenConn int    `yaml:"max_open_conns"`
			LogMode     bool   `yaml:"log_mode"`
		} `yaml:"mysql"`
		SQLite struct {
			Path string `yaml:"path"`
		} `yaml:"sqlite"`
	} `yaml:"database"`

	JWT struct {
		Secret     string `yaml:"secret"`
		ExpireTime int    `yaml:"expire_time"`
	} `yaml:"jwt"`

	Log struct {
		Level      string `yaml:"level"`
		Filename   string `yaml:"filename"`
		MaxSize    int    `yaml:"max_size"`
		MaxBackups int    `yaml:"max_backups"`
		MaxAge     int    `yaml:"max_age"`
		Compress   bool   `yaml:"compress"`
	} `yaml:"log"`
}

// LoadConfig 从指定路径加载配置
func LoadConfig(configPath string) (*Config, error) {
	config := &Config{}

	file, err := os.Open(configPath)
	if err != nil {
		return nil, fmt.Errorf("无法打开配置文件: %v", err)
	}
	defer file.Close()

	decoder := yaml.NewDecoder(file)
	if err := decoder.Decode(config); err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %v", err)
	}

	return config, nil
}

// GetMySQLDSN 构建MySQL连接字符串
func (c *Config) GetMySQLDSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		c.Database.MySQL.Username,
		c.Database.MySQL.Password,
		c.Database.MySQL.Host,
		c.Database.MySQL.Port,
		c.Database.MySQL.DBName,
		c.Database.MySQL.Charset,
	)
} 